package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

// 两数相加
func main() {
	l1 := &ListNode{Val: 9}
	l1.Next = &ListNode{Val: 9}

	l2 := &ListNode{Val: 9}
	l2.Next = &ListNode{Val: 9}
	l2.Next.Next = &ListNode{Val: 9}

	ans := addTwoNumbers(l1, l2)

	for ans != nil {
		fmt.Println(ans.Val)
		ans = ans.Next
	}
}

// addTwoNumbers 模拟十位数加法进位运算，不能转成正数型后再计算
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	var p1 = l1
	var p2 = l2
	var ans = &ListNode{}
	var ret = ans
	var forward = 0         // 进位
	var b1, b2 = true, true // l1,l2 遍历有没有结束
	for b1 || b2 {
		ans.Val = (p1.Val + p2.Val + forward) % 10
		forward = (p1.Val + p2.Val + forward) / 10
		p1 = p1.Next
		p2 = p2.Next

		if p1 == nil {
			b1 = false
			p1 = &ListNode{}
		}
		if p2 == nil {
			b2 = false
			p2 = &ListNode{}
		}

		if b1 || b2 { // 如果没遍历完继续创建节点
			ans.Next = &ListNode{}
			ans = ans.Next
		} else if forward != 0 { // 如果已经遍历完了还有一位进位就放最高位
			ans.Next = &ListNode{}
			ans = ans.Next
			ans.Val = forward
		}

	}
	return ret
}
